package com.sky.controller.admin;

/**
 * @Description CommonController
 * @Author liuqiang
 * @Date 2024/2/19
 */

import com.sky.constant.MessageConstant;
import com.sky.result.Result;
import com.sky.utils.AliOssUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.util.UUID;

/**
 * 通用接口
 */
@RestController
@RequestMapping("/admin/common")
@Api(tags = "通用接口")
@Slf4j
public class CommonController {
    @Autowired
    private AliOssUtil aliOssUtil;

    /**
     * 阿里云OSS文件上传
     * @param file
     * @return
     */
    @ApiOperation("阿里云OSS文件上传")
    @PostMapping("/upload")
    public Result<String> upload(MultipartFile file){
        log.info("文件上传，file={}",file);
        //调用工具类中的upload方法得到文件的存储路径 String upload(byte[] bytes, String objectName)
        try {
            //得到原始文件名
            String filename = file.getOriginalFilename();
            //得到文件的后缀名 .png
            String suffix = filename.substring(filename.lastIndexOf("."));
            //创建新的文件名
            String newFilename = UUID.randomUUID() + suffix;
            //调用upload方法得到文件的存储路径
            String filePath = aliOssUtil.upload(file.getBytes(), newFilename);
            //返回文件存储路径
            return Result.success(filePath);
        } catch (IOException e) {
            //文件上传失败
            log.error(MessageConstant.UPLOAD_FAILED + ":" + e);
        }
        //文件上传失败，返回错误信息
        return Result.error(MessageConstant.UPLOAD_FAILED);
    }
}
